package com.yzg.shared;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author misterWei
 * @create 2020年04月12号:22点24分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.shared")
public class SharedVariable {


    public static void main(String[] args) throws InterruptedException {

        //TestThread();
        ThreadLock threadLock = new ThreadLock();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    threadLock.method1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();
        }
        threadLock.method1();

    }
    static int j = 0;
    private static void TestThread() throws InterruptedException {
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                j++;
            }
        },"t1");

        Thread thread2 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                j--;
            }
        },"t2");
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        log.debug(String.valueOf(j));
    }

    static class ThreadLock{
       private   final  Object lock = new Object();
        private   final  Object lock2 = new Object();

        public void method1() throws InterruptedException {
             synchronized (lock){

                 System.out.println(1);
                 TimeUnit.SECONDS.sleep(1);
                     method2();
             }
         }
         public void method2(){
             synchronized (lock){
                 System.out.println(2);
             }
         }

    }
}
